﻿using CubicFWNet.Application.SystemManager;
using CubicFWNet.Common;
using CubicFWNet.Data.Models;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Linq;
using CubicFWNet.Application;
using CubicFWNet.Mvc.Models;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace CubicFWNet.Mvc
{
    [HandlerLogin]
    public abstract class ControllerBase : Controller
    {
        protected Response Result = new Response();
        private  static  readonly  ModuleApp app= new ModuleApp();
        public Log FileLog
        {
            get { return LogFactory.GetLogger(this.GetType().ToString()); }
        }

        protected CubicFWNet.Data.Models.Module CurrentModule;
        protected List<CubicFWNet.Data.Models.Module> UserModules;
        protected OperatorModel operatorModel;
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            string controllername = Request.RequestContext.RouteData.Values["controller"].ToString().ToLower();
            string actionname = Request.RequestContext.RouteData.Values["action"].ToString().ToLower();
            operatorModel = OperatorProvider.Provider.GetCurrent();
            if (operatorModel == null)
            {
                WebHelper.WriteCookie("cubic_login_error", "overdue");
                //filterContext.HttpContext.Response.Write("<script>top.location.href = '/Login/Index';</script>");
                filterContext.Result = new RedirectResult("/Login/Index");
                return;
            }
            UserModules = app.LoadForUser(operatorModel.UserId, operatorModel.IsSystem);

            ViewBag.UserModules = UserModules;

            CurrentModule = UserModules.FirstOrDefault(u => u.Url != null && u.Url.ToLower().Contains(controllername) && u.Url.ToLower().Contains(actionname));
            if (operatorModel.IsSystem)
            {
                return;
            }
            string currentaction = filterContext.ActionDescriptor.ActionName.ToLower();
            var function = this.GetType().GetMethods().FirstOrDefault(u => u.Name.ToLower() == currentaction);
            if (function == null)
                throw new Exception("未能找到Action");
               var authorize = function.GetCustomAttribute(typeof(AuthenticateAttribute));
            //var authorize = this.GetType().GetCustomAttribute(typeof(AuthenticateAttribute));
            //当前登录用户没有Action记录&&Action有authenticate标识
            if (authorize != null && CurrentModule == null)
            {
                WebHelper.WriteCookie("cubic_login_error", "overdue");
                //filterContext.HttpContext.Response.Write("<script>top.location.href = '/Login/Index';</script>");
                filterContext.Result = new RedirectResult("/Login/Index");
                return;
            }

        }

    }
}
